<template>
  <div class="cart">
    <h2>购物车</h2>
    <div v-if="cartItems.length === 0" class="empty-cart">
      购物车为空
    </div>
    <div v-else>
      <div 
        v-for="item in cartItems" 
        :key="item.id"
        class="cart-item"
      >
        <h4>{{ item.name }}</h4>
        <p>¥{{ item.price }}</p>
        <div class="quantity-controls">
          <button @click="$emit('update-quantity', item.id, item.quantity - 1)">-</button>
          <span>{{ item.quantity }}</span>
          <button @click="$emit('update-quantity', item.id, item.quantity + 1)">+</button>
        </div>
        <button 
          @click="$emit('remove-item', item.id)"
          class="remove-btn"
        >
          删除
        </button>
      </div>
      <div class="cart-total">
        <strong>总计: ¥{{ total }}</strong>
      </div>
      <button 
        @click="$emit('checkout')"
        class="checkout-btn"
      >
        去结算
      </button>
    </div>
  </div>
</template>

<script setup>
import { computed } from 'vue'

const props = defineProps(['cartItems'])
defineEmits(['update-quantity', 'remove-item', 'checkout'])

const total = computed(() =>
  props.cartItems.reduce((sum, item) => sum + item.price * item.quantity, 0)
)
</script>

<style scoped>
.cart {
  background: #f8f9fa;
  padding: 1rem;
  border-radius: 8px;
}

.cart-item {
  border-bottom: 1px solid #ddd;
  padding: 1rem 0;
}

.quantity-controls {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin: 0.5rem 0;
}

.checkout-btn {
  width: 100%;
  background: #28a745;
  color: white;
  border: none;
  padding: 1rem;
  border-radius: 4px;
  cursor: pointer;
  margin-top: 1rem;
}
</style>